package data

import (
	"context"
	e "errors"
	"gitee.com/shuokeyun/kratos/errors"
	"gitee.com/shuokeyun/merchant-service/internal/domain"
	"github.com/go-redis/redis/v8"
	"strconv"
)

var ErrCacheStoreFail = e.New("result fell short of expectations")

var _ domain.MerchantCacheRepo = (*merchantCache)(nil)

type merchantCache struct {
	redis *redis.Client
	hKey  string
}

func NewMerchantCacheRepo(redis *redis.Client) domain.MerchantCacheRepo {
	return &merchantCache{
		redis: redis,
		hKey:  "ms:merchant",
	}
}

func (m *merchantCache) GetMerchant(ctx context.Context, id int32) (*domain.Merchant, error) {
	sCmd := m.redis.HGet(ctx, m.hKey, m.hashField(id))
	if sCmd.Err() != nil {
		if sCmd.Err() == redis.Nil {
			return nil, nil
		}
		return nil, errors.ErrorDBWrap(sCmd.Err(), "redis hget error")
	}
	var merchant domain.Merchant
	if err := sCmd.Scan(&merchant); err != nil {
		return nil, err
	}
	return &merchant, nil
}

func (m *merchantCache) SetMerchant(ctx context.Context, merchant *domain.Merchant) error {
	n, err := m.redis.HSet(ctx, m.hKey, m.hashField(merchant.Id), merchant).Result()
	if err != nil {
		return err
	}
	if n != 1 {
		return ErrCacheStoreFail
	}
	return nil
}

func (m *merchantCache) hashField(id int32) string {
	return strconv.Itoa(int(id))
}
